const path = require('path');
const fs = require('fs');
const dirTree = require("directory-tree");

const argv = require('minimist')(process.argv.slice(2));
const dir = argv.dir;
const exclude = argv.exclude.split(',').join('|');


const cleanFile = file => {
  if (
    fs.existsSync(file)
    && fs.readFileSync(file, 'utf8').trim()
  ) {
    fs.writeFileSync(file, '')
  }
}

function generateDirTree(dir, callback) {

 return dirTree(dir, {
    // extensions: /\.(md|js|html|java|py|rb)$/
    extensions: /\.(md)$/,
    exclude: new RegExp(exclude),
    normalizePath: true,
  }, function (item, path, stats) {
   callback && callback(item, path, stats);
  });

}

function createFile(dir) {
  const to = path.resolve(__dirname, `./data/${dir}.json`)
  cleanFile(to);

  const generate = () => {
    const tree = generateDirTree(dir);
    const treeString = JSON.stringify(tree);
    const to = path.resolve(__dirname, `./data/${dir}.json`);
    if (
      fs.existsSync(to) &&
      fs.readFileSync(to, 'utf8').trim() === treeString.trim()
    ) {
      return
    }
    fs.writeFileSync(to, treeString)
  };
  generate()
}

createFile(dir);
